"""FastAPI应用入口"""
from fastapi import FastAPI
from fastapi.exceptions import RequestValidationError
from starlette.exceptions import HTTPException as StarletteHTTPException
from datetime import datetime

from app.config import settings
from app.database import engine, Base
from app.middleware.cors import setup_cors
from app.middleware.error_handler import (
    validation_exception_handler,
    http_exception_handler,
    general_exception_handler,
)
from app.utils.logger import logger
from app.api.v1 import api_router

# 创建FastAPI应用
app = FastAPI(
    title=settings.APP_NAME,
    version=settings.APP_VERSION,
    description="质量看板系统API",
    docs_url="/api/docs",
    redoc_url="/api/redoc",
)

# 注册API路由
app.include_router(api_router)

# 配置CORS
setup_cors(app)

# 注册异常处理器
app.add_exception_handler(RequestValidationError, validation_exception_handler)
app.add_exception_handler(StarletteHTTPException, http_exception_handler)
app.add_exception_handler(Exception, general_exception_handler)


@app.on_event("startup")
async def startup_event():
    """应用启动事件"""
    logger.info("Application startup", app_name=settings.APP_NAME, version=settings.APP_VERSION)
    # 创建数据库表（开发环境，生产环境应使用迁移）
    if settings.DEBUG:
        Base.metadata.create_all(bind=engine)


@app.on_event("shutdown")
async def shutdown_event():
    """应用关闭事件"""
    logger.info("Application shutdown")


@app.get("/")
async def root():
    """根路径"""
    return {
        "name": settings.APP_NAME,
        "version": settings.APP_VERSION,
        "status": "running",
        "timestamp": datetime.now().isoformat(),
    }


@app.get("/health")
async def health_check():
    """健康检查"""
    return {
        "status": "healthy",
        "timestamp": datetime.now().isoformat(),
    }

